import 'package:flutter/material.dart';
import 'record_button.dart'; // 导入之前创建的录音按钮


/** 安全关闭
    // 假设这是在您的某个Widget中
    RecordBottomSheetHandle? _bottomSheetHandle;

    void _showRecordSheet() {
    _bottomSheetHandle = RecordBottomSheet.show(
    context: context,
    text: "请说话...",
    // ... 其他参数
    onDismiss: () {
    _bottomSheetHandle = null; // 清理handle
    print("BottomSheet dismissed");
    },
    );
    }

    void _closeRecordSheetExternally() {
    if (_bottomSheetHandle != null && _bottomSheetHandle!.isShowing) {
    bool closed = _bottomSheetHandle!.close();
    if (closed) {
    print("BottomSheet closed externally");
    } else {
    print("Failed to close BottomSheet externally (already closing or not showing)");
    }
    } else {
    print("BottomSheet is not showing or handle is null");
    }
    }
 */

// Typedefs
typedef RecordPermissionCallback = Future<bool> Function();
typedef RecordStartCallback = void Function();
typedef RecordEndCallback = void Function(Duration duration, String filePath);
typedef RecordPermissionPermanentlyDeniedCallback = void Function();

// The UI content of the bottom sheet
class _RecordBottomSheetContent extends StatelessWidget {
  final String text;
  final RecordPermissionCallback onNeedPermission;
  final RecordStartCallback onRecordStart;
  final RecordEndCallback onRecordEnd;
  final RecordPermissionPermanentlyDeniedCallback? onPermissionPermanentlyDenied;

  const _RecordBottomSheetContent({
    Key? key,
    required this.text,
    required this.onNeedPermission,
    required this.onRecordStart,
    required this.onRecordEnd,
    this.onPermissionPermanentlyDenied,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // Define constants for layout to make adjustments easier
    const double recordButtonBottomMargin = 20.0;
    // Estimated max height of RecordButton:
    // 44 (button base height)
    // + ~18 (text height for "松开取消" etc., font size 16)
    // + 8 (padding below that text)
    // = ~70 (actual height of RecordButton's content when hint text is shown)
    const double recordButtonEstimatedMaxHeight = 70.0;
    const double spacingAboveRecordButton = 16.0; // Space between text content and top of RecordButton area

    // This is the space from the bottom of the sheet that the content area (text + close button) should not enter.
    // It includes the RecordButton's max height, its bottom margin, and desired spacing.
    final double contentAreaBottomOffset = recordButtonBottomMargin + recordButtonEstimatedMaxHeight + spacingAboveRecordButton;

    return Container(
      // The BottomSheet itself should determine its height.
      // We ensure the Container tries to fill the width.
      width: double.infinity,
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      child: Stack(
        children: [
          // Content Area (Text and Close Button)
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            // Reserve space at the bottom for the RecordButton and its margins/spacing
            bottom: contentAreaBottomOffset,
            child: Column(
              children: [
                Align(
                  alignment: Alignment.topRight,
                  child: Padding(
                    padding: const EdgeInsets.only(top: 8.0, right: 8.0), // Add some padding for the close button
                    child: IconButton(
                      icon: const Icon(Icons.close, color: Colors.grey),
                      onPressed: () => Navigator.of(context).pop(),
                    ),
                  ),
                ),
                const Text("请朗读",textAlign: TextAlign.center,
                  style: TextStyle(fontSize: 22, color: Colors.black87,fontWeight: FontWeight.w900),),
                Expanded(
                  child: Center(
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 24.0),
                      child: Text(
                        text,
                        textAlign: TextAlign.center,
                        style: const TextStyle(fontSize: 20, color: Colors.black87),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          // RecordButton Area
          Positioned(
            // Horizontally center the RecordButton which has a fixed width of 320.
            // This Positioned widget itself will span the full width due to left:0, right:0,
            // then Align will center the RecordButton within it.
            left: 0,
            right: 0,
            bottom: recordButtonBottomMargin, // Fixed margin from the bottom of the Stack
            child: Align(
              alignment: Alignment.center, // Center the RecordButton horizontally
              child: RecordButton(
                onNeedPermission: onNeedPermission,
                onRecordStart: onRecordStart,
                onRecordEnd: onRecordEnd,
                onPermissionPermanentlyDenied: onPermissionPermanentlyDenied,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

// Forward declaration for the handle
class RecordBottomSheetHandle {
  // This context should be the one from within the builder of showModalBottomSheet
  // or a child of it, so that Navigator.of(context).pop() targets the bottom sheet.
  BuildContext? _routeContext;
  bool _isShowing = false;

  // Called by RecordBottomSheet.show to set the context
  void _setContext(BuildContext context) {
    _routeContext = context;
    _isShowing = true;
  }

  // Called when the bottom sheet is dismissed naturally
  void _onDismiss() {
    _isShowing = false;
    _routeContext = null; // Clear context to prevent misuse
  }

  /// Returns true if the bottom sheet is currently considered to be showing.
  bool get isShowing => _isShowing;

  /// Attempts to close the bottom sheet if it is showing.
  /// Returns true if a pop was attempted, false otherwise.
  bool close() {
    if (_isShowing && _routeContext != null && _routeContext!.mounted) {
      Navigator.of(_routeContext!).pop();
      // _isShowing will be set to false by the whenComplete callback.
      return true;
    }
    return false;
  }
}

// Class to provide the static show method, making the API consistent
class RecordBottomSheet {
  static RecordBottomSheetHandle show({ // Changed return type
    required BuildContext context,
    required String text,
    double topOffset = 77.0, // Default distance from the top
    VoidCallback? onDismiss, // Callback when the sheet is dismissed
    required RecordPermissionCallback onNeedPermission,
    required RecordStartCallback onRecordStart,
    required RecordEndCallback onRecordEnd,
    RecordPermissionPermanentlyDeniedCallback? onPermissionPermanentlyDenied,
  }) {
    final handle = RecordBottomSheetHandle();
    final screenHeight = MediaQuery.of(context).size.height;
    // Calculate the actual height for the content part of the sheet
    final contentMaxHeight = screenHeight - topOffset;

    showModalBottomSheet<void>(
      context: context,
      isScrollControlled: true, // Important for custom height and avoiding keyboard overlap
      backgroundColor: Colors.transparent, // Sheet's own background is transparent
      barrierColor: Colors.black54.withOpacity(0.5), // Dimming effect for the background
      builder: (BuildContext builderContext) { // This is the crucial context
        // builderContext is the context of the modal route.
        // Popping from this context will close the bottom sheet.
        handle._setContext(builderContext); // Pass this context to the handle

        // This Padding widget creates the visual offset from the top of the screen.
        // The area above the sheet content (within topOffset) will be part of the barrier.
        return Padding(
          padding: EdgeInsets.only(top: topOffset),
          child: SizedBox( // Use SizedBox to explicitly set the height of the content area
            height: contentMaxHeight,
            child: _RecordBottomSheetContent(
              text: text,
              onNeedPermission: onNeedPermission,
              onRecordStart: onRecordStart,
              onRecordEnd: onRecordEnd,
              onPermissionPermanentlyDenied: onPermissionPermanentlyDenied,
            ),
          ),
        );
      },
    ).whenComplete(() {
      // Trigger the onDismiss callback when the sheet is fully closed
      handle._onDismiss(); // Notify handle that sheet is dismissed
      if (onDismiss != null) {
        onDismiss();
      }
    });

    return handle; // Return the handle
  }
}